<template>
    <div class="demand-detail">
        <a-modal width="1300px" :visible="visible" title="编辑需求" @cancel="closeModal" class="yuan-modal demand-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '150px' } }" :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel">
                        <div class="form-panel-box">
                            <div v-show="!isNext || isShow">
                                <a-form-model-item label="封面图" class="yuan-form-item" v-if="pageReady">
                                    <UploadVue :uploadLength="1" @uploadChange="uploadChangeCoverImageUrl"
                                        :defImgList="formData.coverImageUrl?[formData.coverImageUrl]:[]" />
                                    <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                                </a-form-model-item>
                                <div class="form-title">
                                    需求类型
                                </div>
                                <a-form-model-item class="yuan-form-row" label="">
                                    <a-radio-group v-model="formData.demandType">
                                        <a-radio value="本人需求">本人需求</a-radio>
                                        <a-radio value="委托方需求">委托方需求</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <template v-if="formData.demandType==='委托方需求'">
                                    <div class="form-title">
                                        委托人信息
                                    </div>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人企业/单位名称"
                                        prop="clientCompanyName">
                                        <a-input class="yuan-form-input" v-model="formData.clientCompanyName"
                                            placeholder="请输入委托人企业/单位名称"></a-input>
                                    </a-form-model-item>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人姓名" prop="clientName">
                                        <a-input class="yuan-form-input" v-model="formData.clientName"
                                            placeholder="请输入委托人姓名"></a-input>
                                    </a-form-model-item>
                                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="委托人联系方式" prop="clientContact">
                                        <a-input class="yuan-form-input" v-model="formData.clientContact"
                                            placeholder="请输入委托人联系方式"></a-input>
                                    </a-form-model-item>
                                </template>

                                <div class="form-title">
                                    需求基本信息
                                </div>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="需求名称" prop="demandName">
                                    <a-input class="yuan-form-input" v-model="formData.demandName" placeholder="需求名称"></a-input>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="分类" prop="category">
                                    <a-radio-group v-model="formData.category">
                                        <a-radio value="生产研发需求">生产研发需求</a-radio>
                                        <a-radio value="技术服务需求">技术服务需求</a-radio>
                                        <a-radio value="临床效果需求">临床效果需求</a-radio>
                                        <a-radio value="生产技术需求">生产技术需求</a-radio>
                                        <a-radio value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.categoryOther" :maxNum="15" placeholder="请输入" />
                                        </a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="细分领域" prop="subCategory">
                                    <a-checkbox-group v-model="formData.subCategory">
                                        <a-checkbox :value="item.content" v-for="item in territoryList"
                                            :key="item.id">{{item.content}}</a-checkbox>
                                        <a-checkbox value="其他">
                                            <span>其他：</span>
                                            <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                                v-model="formData.subCategoryOther" :maxNum="15" placeholder="请输入" />
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="企业/单位名称" prop="companyName">
                                    <a-input class="yuan-form-input" v-model="formData.companyName"
                                        placeholder="请输入企业/单位名称"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="联系人" prop="contacts">
                                    <a-input class="yuan-form-input" v-model="formData.contacts" placeholder="请输入联系人"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="联系方式" prop="contactInfo">
                                    <a-input class="yuan-form-input" v-model="formData.contactInfo"
                                        placeholder="请输入联系方式"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="技术简介" prop="technicalDescription">
                                    <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                        v-model="formData.technicalDescription" placeholder="请输入技术简介" :maxLength="500" />
                                </a-form-model-item>

                            </div>
                            <div v-show="isNext || isShow">
                                <div class="form-title">
                                    其他信息
                                </div>
                                <a-form-model-item class="yuan-form-row" label="拟投入金额" prop="investmentMin">
                                    <a-input class="yuan-form-input" v-model="formData.investmentMin" placeholder="请输入"></a-input>
                                    <span>~</span>
                                    <a-input class="yuan-form-input" v-model="formData.investmentMax" placeholder="请输入"></a-input>
                                    <span> 万元</span>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="需求截止时间" prop="deadline">
                                    <a-date-picker class="yuan-form-input" placeholder="需求截止时间" v-model="formData.deadline"
                                        inputReadOnly valueFormat="YYYY-MM-DD" @change="deadlineChange" />
                                    <span v-show="formData.deadline"> 剩余：{{formData.deadlineDay}}天</span>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="需求发布地址" prop="placeAreaCode">
                                    <a-cascader class="yuan-form-input" v-model="formData.placeAreaCode" :options="addrData"
                                        placeholder="请选择" @change="onAddrChange" />
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="其他" prop="otherDetails">
                                    <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                        v-model="formData.otherDetails" placeholder="请输入" :maxLength="500" />
                                </a-form-model-item>
                                <a-form-model-item label="介绍图片" class="yuan-form-item" v-if="pageReady">
                                    <UploadVue :uploadLength="3" @uploadChange="uploadChangeIntroImageUrl"
                                        :defImgList="formData.introImageUrl?formData.introImageUrl:[]" />
                                    <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item" label="介绍视频" prop="introVideoUrl">
                                    <a-input class="yuan-form-input" style="max-width:500px" v-model="formData.introVideoUrl"
                                        placeholder="请输入视频地址"></a-input>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="授权经纪人">
                                    <div v-for="(item,idx) in formData.brokerRelevances">
                                        <span style="display:inline-block;width:200px;border-bottom: solid 1px #eee;">{{item.technicalRepresentative}}</span>
                                        <a-button type="danger" @click="delUser(idx)" v-if="!isShow">移除</a-button>
                                    </div>
                                    <div></div>
                                    <a-button type="primary" @click="()=>userVisible=true" v-if="!isShow">选择技术经纪人</a-button>
                                </a-form-model-item>

                                <a-form-model-item class="yuan-form-row" label="需求描述" prop="synopsis">
                                    <div class="editor" style="min-height:300px;width:1000px">
                                        <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef"
                                            :defaultConfig="editorConfig.toolbarConfig" mode="default" />
                                        <Editor v-model="formData.synopsis" :defaultConfig="editorConfig" mode="default"
                                            @onCreated="handleCreated" />
                                    </div>
                                </a-form-model-item>
                            </div>
                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <template v-if="isShow">
                    <a-button type="primary" @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="isNext=true" type="warning" :loading="saveLoading" v-if="!isNext">
                        下一步
                    </a-button>
                    <a-button @click="isNext=false" type="warning" :loading="saveLoading" v-else>
                        上一步
                    </a-button>
                    <a-button @click="modalOk" type="primary" :loading="saveLoading" v-if="isNext">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>

            </template>

            <UserVue :visible="userVisible" @closeModal="() => userVisible = false" @sureClose="selectUser" />
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import UserVue from "@/components/addUserModal.vue";
import areaJson, { getAreaWords } from "@/utils/area";
import api from "@/api/api";
import CountInputVue from "@/components/countInput.vue";
import { MENU_CONF, toolbarConfig } from "@/utils/wangeditors";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
@Component({
    name: "tpl",
    components: { UploadVue, UserVue, CountInputVue, Editor, Toolbar },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editId!: string;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            if (this.editId) {
                this.getDetailInfo();
            } else {
                this.formData = {brokerRelevances:[]};
                this.pageReady = true;
            }
        } else {
            this.pageReady = false;
        }
    }
    isNext = false;
    saveLoading = false;
    formData: any = {
        brokerRelevances:[]
    };
    rules = {
        demandName: [{ required: true, message: "请输入需求名称", trigger: "change" }],
        technicalDescription: [{ required: true, message: "请输入技术简介", trigger: "change" }],
        category: [{ required: true, message: "请选择分类", trigger: "change" }],
        subCategory: [{ required: true, message: "请选择细分领域", trigger: "change" }],
        //investmentMin: [{ required: true, message: "请填写投入金额", trigger: "change" }],
        companyName: [{ required: true, message: "请填写企业单位名称", trigger: "change" }],
        contacts: [{ required: true, message: "请填写联系人", trigger: "change" }],
        contactInfo: [{ required: true, message: "请填写联系方式", trigger: "change" }],
        //deadline: [{ required: true, message: "请选择截至时间", trigger: "change" }],
        //placeAreaCode: [{ required: true, message: "请选择发布地址", trigger: "change" }],
        synopsis: [{ required: true, message: "请填写需求描述", trigger: "change" }],
    };
    pageReady = false;
    userVisible = false;

    async mounted() {
        this.setAddrData();
        this.getTerritoryList();
    }
    closeModal() {
        this.$emit("closeModal");
    }

    async getDetailInfo() {
        this.saveLoading = true;
        try {
            const res = await api.getDemandList({ id: this.editId });
            res.data.introImageUrl = res.data.introImageUrl ? JSON.parse(res.data.introImageUrl) : [];
            res.data.demandType = res.data.differentiateDemand || "本人需求";
            res.data.placeAreaCode = res.data.code ? res.data.code.split(",") : [];
            res.data.synopsis=res.data.synopsis||''
            this.otherArr.forEach((item) => {
                if (typeof res.data[item] === "string") {
                    if (res.data[item].indexOf("其他-") >= 0) {
                        const val = res.data[item].split("-");
                        res.data[item] = "其他";
                        res.data[item + "Other"] = val[1];
                    }
                } else if (typeof res.data[item] === "object" && res.data[item]) {
                    res.data[item] = res.data[item].map((child) => {
                        if (child.indexOf("其他-") >= 0) {
                            const val = child.split("-");
                            res.data[item + "Other"] = val[1];
                            return "其他";
                        } else {
                            return child;
                        }
                    });
                }
            });

            this.formData = res.data;
            this.pageReady = true;
        } finally {
            this.saveLoading = false;
        }
    }

    otherArr = ["category", "subCategory"];
    async modalOk() {
        if (!this.formData.demandType) {
            this.$message.error("请选择需求类型");
            return;
        }
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const data = {
                    ...this.formData,
                    coverImageUrl:this.formData.coverImageUrl?this.formData.coverImageUrl:'https://zyykjcgzhxt.cdutcm.edu.cn/picture/moren.png',
                    ifDeliver: 0,
                    sign:'后台',
                    differentiateDemand: this.formData.demandType,
                };

                this.otherArr.forEach((item) => {
                    if (typeof data[item] === "string") {
                        if (data[item] === "其他") {
                            data[item] = "其他-" +  (data[item + "Other"] || '');
                        }
                    } else if (typeof data[item] === "object" && data[item]) {
                        data[item] = data[item].map((child) => {
                            if (child === "其他") {
                                return "其他-" +  (data[item + "Other"] || '');
                            } else {
                                return child;
                            }
                        });
                    }
                });

                const res = await api.addDemand(data);
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }
    uploadChangeHead(e) {
        this.formData.headPortrait = e.length ? e[0].url : "";
    }
    uploadChangeCoverImageUrl(e) {
        this.formData.coverImageUrl = e.length ? e[0].url : "";
    }
    uploadChangeIntroImageUrl(e) {
        this.formData.introImageUrl = e.map((item) => item.url);
    }
    addrData: any[] = [];
    setAddrData() {
        this.addrData = areaJson;
    }

    territoryList = [];
    async getTerritoryList() {
        try {
            this.saveLoading = true;
            const res = await api.getSetting("3");
            this.territoryList = res.data;
        } finally {
            this.saveLoading = false;
        }
    }

    deadlineChange() {
        if (!this.formData.deadline) return "";
        const nowTime = new Date().getTime();
        const deadlineTime = new Date(this.formData.deadline.replace(/-/g, "/")).getTime();
        const day = (deadlineTime - nowTime) / (24 * 60 * 60 * 1000);
        this.formData.deadlineDay = Math.ceil(day);
    }
    onAddrChange(e: any) {
        this.formData.code = e.join(",");
        this.formData.location = getAreaWords(e);
    }

    selectUser(userInfo) {
        if (this.formData.brokerRelevances) {
            this.formData.brokerRelevances.push({
                technicalRepresentative: userInfo.name,
                technicalHeadPortrait: userInfo.headPortrait,
                technicalPhone: userInfo.phone,
            });
        } else {
            this.formData.brokerRelevances = [
                {
                    technicalRepresentative: userInfo.name,
                    technicalHeadPortrait: userInfo.headPortrait,
                    technicalPhone: userInfo.phone,
                },
            ];
        }
    }
    delUser(idx) {
        this.formData.brokerRelevances.splice(idx, 1);
    }
    editorRef = null;
    editorConfig = {
        placeholder: "请输入内容...",
        //配置工具栏
        toolbarConfig: toolbarConfig,
        MENU_CONF: MENU_CONF,
    };
    handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例
    }
}
</script>
<style lang="scss">
.demand-detail-modal {
    .form-title {
        font-size: 16px;
        color: #204fb6;
        padding: 10px 0;
        border-bottom: solid 1px #eee;
        display: flex;
        align-items: center;
        margin-bottom: 5px;
    }
    .form-title::before {
        content: "";
        display: inline-block;
        height: 15px;
        width: 3px;
        background-color: #204fb6;
        margin-right: 8px;
    }
    .yuan-form-row {
        margin-bottom: 20px;
        
        .ant-checkbox-wrapper,.ant-radio-wrapper{
            line-height: 40px;
        }
    }
}
</style>
